import store from '@/store'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  /* 注册 */
  {
    path: '/reg',
    component: () => import('@/views/register')
  },
  /* 登录 */
  {
    path: '/login',
    component: () => import('@/views/login')
  },
  /* 主页 */
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/home', // 默认显示首页的二级路由
    children: [
      {
        path: 'home',
        component: () => import('@/views/home')
      },
      {
        path: 'user-info',
        component: () => import('@/views/user/userInfo.vue')
      },
      {
        path: 'user-avatar',
        component: () => import('@/views/user/userAvatar.vue')
      },
      {
        path: 'user-pwd',
        component: () => import('@/views/user/userPwd.vue')
      },
      {
        path: 'art-cate',
        component: () => import('@/views/article/artCate.vue')
      },
      {
        path: 'art-list',
        component: () => import('@/views/article/artList.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
const whiteList = ['/login', '/reg']
router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (token) {
    /* 如果有token 证明已经登录 */
    if (!store.state.userInfo.username) {
      /* 有token但是没有用户信息 才去请求用户信息保存到vuex里 */
      /* 调用action里面的方法去请求数据 */
      store.dispatch('initUserInfo')
    }
    /* 路由放行 */
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      /* 如果去其他页面强制拦截并跳转到登录页面 */
      next('/login')
    }
  }
})

export default router
